<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="username" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ index >= 10 ? index + 1 : "0" + (index + 1) }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")) || [],
      username: "",
      age: "",
      gender: "",
      index: 0,
      flag: 0,
    };
  },
  methods: {
    // 添加/修改
    add() {
      if (!this.username || !this.age || !this.gender) {
        alert("信息不完整，无法添加");
        return;
      } else if (this.flag == 1) {
        (this.list[this.index].name = this.username),
          (this.list[this.index].age = this.age),
          (this.list[this.index].gender = this.gender);
      } else {
        const obj = {
          name: this.username,
          age: this.age,
          gender: this.gender,
          id: +new Date(),
        };
        this.list.push(obj);
      }
      this.username = "";
      this.age = "";
      this.gender = "";
    },
    // 删除功能
    del(id) {
      // findIndex方法
      // const num = this.list.findIndex((item) => item.id === id);
      // this.list.splice(num, 1);
      // filter方法
      this.list = this.list.filter((item) => item.id !== id);
    },
    // 编辑
    edit(id) {
      this.flag = 1;
      this.username = this.list[id].name;
      this.age = this.list[id].age;
      this.gender = this.list[id].gender;
      this.index = id;
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newValue) {
        localStorage.setItem("list", JSON.stringify(newValue));
      },
    },
  },
};
</script>
<style scoped>
table {
  text-align: center;
}
</style>
